package com.sky.business.sys.mqtt.listener;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.business.sys.domain.MQTTMessage;
import com.sky.business.sys.domain.SystemConfig;
import com.sky.business.sys.handler.mgr.CmccEventHandlerManager;
import com.sky.business.sys.queue.MQTTMessageQueueConfig;
import com.sky.business.sys.service.SystemConfigService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.SimpleTimeZone;

/**
 * cmcc消息监听器
 */
@Component
@Slf4j
public class CMCCDispatcherCallbackListener implements IMqttMessageListener, InitializingBean {

    @Autowired
    public CmccEventHandlerManager cmccEventHandlerManager;

    @Autowired
    private SystemConfigService systemConfigService;

    public static final ObjectMapper objectMapper = new ObjectMapper().setTimeZone(SimpleTimeZone.getTimeZone("GMT+8"));

    public static String currEdgeId;

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        String messageBody = new String(message.getPayload(), StandardCharsets.UTF_8);
        JsonNode rootNode = objectMapper.readTree(messageBody);
        String edgeId = rootNode.get("edgeId").asText();
        String event = rootNode.get("event").asText();
        if (currEdgeId.equals(edgeId)) {
            log.debug("接收到凌云平台下发的消息:{}",message);
            //保存到数据库
            MQTTMessageQueueConfig.offer(new MQTTMessage(MQTTMessage.Type.DISPATCHER, messageBody));
            //处理事件
            cmccEventHandlerManager.handle(topic,messageBody,event);
        }
    }

    @Override
    public void afterPropertiesSet() {
        SystemConfig systemConfig = systemConfigService.getSystemConfig();
        currEdgeId = systemConfig.getEdgeId();
    }
}
